<?php

namespace App\Http\Controllers\Web\Seller;

use App\ConstDir\ErrorConst;                                                                                         
use App\Http\Controllers\Web\BaseController;
use App\Repository\Repositories\Interfaces\ContractsRepository;
use Illuminate\Http\Request;

/**
 * 合同控制器
 */
class ContractsController extends BaseController
{
    /**
     * @var ContractsRepository
     */
    protected $contracts_repo;

    protected $shop_id;

    public function __construct(ContractsRepository $contracts_repo)
    {
        parent::__construct();

        $this->shop_id = array_get($this->user, 'shop_id');

        $this->contracts_repo = $contracts_repo;
        //用户只能操作自身所属数据
        $this->contracts_repo->scopeQuery(function ($query) {
            return $query->where('shop_id', $this->shop_id);
        });
    }

    public function index(Request $request)
    {
        $contracts = $this->contracts_repo->paginate($this->perPage);
        
        return $this->success(ErrorConst::SUCCESS_CODE, $contracts, true);

    }

    public function show($id)
    {
        $contracts = $this->contracts_repo->find($id);

        return $this->success(ErrorConst::SUCCESS_CODE_MSG, $contracts['data']);
    }

    /**
     * 创建合同
     * @param Request $request
     * @return \Illuminate\Support\Collection
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
            'content' => 'required',
        ],[
            'name.required' => '合同名称不可为空',
            'content.required' => '请填写合同条例',
        ]);
        $data = $request->all('name','content');
//        dd($data);
        $data['shop_id'] = $this->shop_id;
        $ret  = $this->contracts_repo->create($data);
//        dd($ret);

        return $this->noDataReturn($ret ? true : false);
    }

    /**
     * 更新合同字段信息
     * @param Request $request
     */
    public function update(Request $request, $id)
    {
        $data = $request->all();

        $this->validate($request, [
            'name' => 'required',
            'content' => 'required',
        ],[
            'name.required' => '合同名称不可为空',
            'content.required' => '请填写合同条例',
        ]);
        
        $ret = $this->contracts_repo->update($data, $id);

        return $this->noDataReturn($ret ? true : false);
    }

    /**
     * 设为默认合同
     * @param Request $request
     */
    public function updateSetDefault($id)
    {
        $ret = $this->contracts_repo->setDefault($id);
        return $this->noDataReturn($ret ? true : false);
    }

    /**
     * 软删除合同
     * @param Request $request
     */
    public function delete($id)
    {
        $ret = $this->contracts_repo->delete($id);
        return $this->noDataReturn($ret ? true : false);
    }
}
